package control

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"strings"
	"time"

	. "gopkg.in/mgo.v2/bson"

	"gopkg.in/mgo.v2"
)

const (
	MGO_COLL_SESSION = "session"
)

func init() {
	http.HandleFunc("/data/schsession", schsession)
}

// data := M{"clientid": sess.GetClientId(), "ip": sess.GetMQTTConner().RemoteAddr().String()}
// data["username"] = sess.GetConnectMessagePacket().GetUserNameByString()
// data["stime"] = time.Now()
// data["msgtype"] = packet.GetTypeName(msg.GetHeaderType())
// data["msg"] = msg.String()
// data["type"] = t
// data["datalen"] = msg.GetDataLen()

type sessions struct {
	Datas     []*session
	MaxCount  int
	CurPage   int
	TotalPage int
}

type session struct {
	Clientid    string `bson:"_id"`
	ServerName  string `bson:"serverName"`
	Online      bool   `bson:"online"`
	Connectprop struct {
		Remoteaddr      string    `bson:"remoteaddr"`
		Createtime      time.Time `json:"createtime"`
		Lastvisitedtime time.Time `json:"lastvisitedtime"`
		Username        string    `json:"username"`
	} `bson:"connectprop"`
	Will struct {
		Flag    bool   `bson:"flag"` //  "flag" : false,
		Topic   string `bson:"topic"`
		Qos     uint8  `bson:"qos"`
		Payload []byte `bson:"payload"` //"payload" : BinData(0,""),
		Retain  bool   `bson:"retain"`  //"retain" : false
	} `bson:"will"`
	Subscribes map[string]uint8 `bson:"subscribes"`

	Distime    time.Time `bson:"distime"`
	OffineMsgs []struct {
		Ppid int64 `bson:"ppid"`
		//Retain   bool   `bson:"retain"`
		Qos uint8 `bson:"qos"`
	} `bson:"offinemsgs"`
	Pub_s_Pub []struct {
		Packetid uint16 `bson:"packetid"`
		Ppid     int64  `bson:"ppid"`
		//Retain   bool   `bson:"retain"`
		Qos uint8 `bson:"qos"`
	} `bson:"pub_s_pub"`
	Pub_s_Pid    []uint16 `bson:"pub_s_pid"`
	Pub_r_Qos2id []uint16 `bson:"pub_r_qos2id"`
}

func schsession(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	curPage, _ := strconv.Atoi(r.FormValue("curPage"))
	count, _ := strconv.Atoi(r.FormValue("count"))
	clientid := r.FormValue("clientid")
	online := r.FormValue("online")
	startdate := r.FormValue("startdate")
	enddate := r.FormValue("enddate")
	result := &sessions{}
	if count == 0 {
		count = 10
	}
	if curPage <= 0 {
		curPage = 1
	}

	clientid = strings.TrimSpace(clientid)
	start := (curPage - 1) * count

	con := M{}

	if clientid != "" {
		con["_id"] = M{"$regex": clientid}
	}
	if online != "" {
		fmt.Println("online:", online)
		if online == "1" {

			con["online"] = true
		} else if online == "0" {
			con["online"] = false
		}
	}

	timeM := M{}
	if startdate != "" {

		date, err := time.Parse("2006-01-02 15:04:05", startdate)
		if err == nil {
			con["connectprop.lastvisitedtime"] = timeM
			timeM["$gte"] = date.Add(-8 * time.Hour)
		} else {
			Tlog.Debug("解析日期格式错误:", err)
		}

	}
	if enddate != "" {

		date, err := time.Parse("2006-01-02 15:04:05", enddate)
		if err == nil {

			con["connectprop.lastvisitedtime"] = timeM
			timeM["$lte"] = date.Add(-8 * time.Hour)
		} else {
			Tlog.Debug("解析日期格式错误:", err)
		}
	}
	Tlog.Debug("查询条件:", con)
	err := GetMyMgo().ExecSync(MGO_COLL_SESSION, func(coll *mgo.Collection) error {

		sum, _ := coll.Find(con).Count()
		result.CurPage = curPage

		if sum == 0 {
			return nil
		}
		result.MaxCount = sum
		result.TotalPage = sum / count
		if sum%count != 0 {
			result.TotalPage++
		}
		var datas = make([]*session, 0)
		err := coll.Find(con).Sort("-connectprop.lastvisitedtime").Skip(start).Limit(count).All(&datas)
		if err != nil {
			return err
		}
		result.Datas = datas
		return nil
	})
	if err != nil {
		io.WriteString(w, fmt.Sprintf("读取数据失败:%v", err))
	}
	data, _ := json.Marshal(result)
	io.WriteString(w, string(data))
}
